package core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.util.HtmlUtils;

import com.alibaba.fastjson.JSON;

import core.modules.base.entity.SysUser;

/**
 * 常用方法：参数获取,时间处理,MD5 SHA-1加密,对象复制 转换
 * 打印,字符串判断,真实IP获取,httpURL,UUID,html转义反转义,url解编码
 * 
 * @author 白俊
 *
 */
public class WebUtil {
	public static final String DATE_FORMART = "yyyy-MM-dd HH:mm:ss";
	public static final String SHORT_DATE_FORMART = "yyyy-MM-dd";
	public static final String DEFAULT_CHARSET = "UTF-8";
	public static final String DEFAULT_METHOD = "POST";

	/**
	 * 获取字符参数 默认返回defaultValue
	 * 
	 * @param request
	 * @param defaultValue
	 * @param key
	 * @return
	 */
	public static String getStr(String key, String defaultValue, HttpServletRequest request) {
		String v = request.getParameter(key);
		if (StringUtils.isBlank(v)) {
			return defaultValue;
		}
		return v;
	}

	/**
	 * 获取字符参数 默认返回null
	 * 
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getStr(String key, HttpServletRequest request) {
		return getStr(key, null, request);
	}

	/**
	 * 获取Date(yyyy-MM-dd HH:mm:ss)参数 默认返回defaultValue
	 * 
	 * @param request
	 * @param key
	 * @return
	 */
	public static Date getDate(String key, Date defaultValue, HttpServletRequest request) {
		try {
			Date d = formatDate(DATE_FORMART, request.getParameter(key));
			if (d == null) {
				return defaultValue;
			}
			return d;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取Date(yyyy-MM-dd)参数 默认返回defaultValue
	 * 
	 * @param request
	 * @param defaultValue
	 * @param key
	 * @return
	 */
	public static Date getShortDate(String key, Date defaultValue, HttpServletRequest request) {
		try {
			Date d = formatDate(SHORT_DATE_FORMART, request.getParameter(key));
			if (d == null) {
				return defaultValue;
			}
			return d;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 字符串格式化成Date
	 * 
	 * @param form
	 *            格式 例如yyyy-MM-dd HH:mm:ss
	 * @param value
	 * @return
	 */
	public static Date formatDate(String form, String value) {
		try {
			return new SimpleDateFormat(form).parse(value);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串(yyyy-MM-dd HH:mm:ss)格式化成Date
	 * 
	 * @param value
	 * @return
	 */
	public static Date formatDate(String value) {
		try {
			return new SimpleDateFormat(DATE_FORMART).parse(value);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串(yyyy-MM-dd)格式化成Date
	 * 
	 * @param value
	 * @return
	 */
	public static Date formatShortDate(String value) {
		try {
			return new SimpleDateFormat(SHORT_DATE_FORMART).parse(value);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取Date字符串yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 * @return
	 */
	public static String getDateStr(Date date) {
		try {
			return new SimpleDateFormat(DATE_FORMART).format(date);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取Date字符串
	 * 
	 * @param form
	 *            格式 例如yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static String getDateStr(String form, Date date) {
		try {
			return new SimpleDateFormat(form).format(date);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取Integer参数
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static Integer getInt(HttpServletRequest request, Integer defaultValue, String key) {
		try {
			return Integer.valueOf(request.getParameter(key));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取Float参数
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static Float getFloat(HttpServletRequest request, Float defaultValue, String key) {
		try {
			return Float.valueOf(request.getParameter(key));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取Double参数
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static Double getDouble(String key, Double defaultValue, HttpServletRequest request) {
		try {
			return Double.valueOf(request.getParameter(key));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取Long参数
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static Long getLong(String key, Long defaultValue, HttpServletRequest request) {
		try {
			return Long.valueOf(request.getParameter(key));
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取数组参数
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static String[] getArray(String key, HttpServletRequest request) {
		return request.getParameterValues(key);
	}

	/**
	 * 获取数组参数,转化为List
	 * 
	 * @param request
	 * @param defaultValue
	 *            默认值
	 * @param key
	 * @return
	 */
	public static List<String> getList(String key, HttpServletRequest request) {
		return Arrays.asList(request.getParameterValues(key));
	}
	
	/**
	 * 转换为驼峰写法
	 * <p>get_it->getIt </p>
	 * <p>LET_IT_GO->letItGo</p>
	 * @param str
	 * @return
	 */
	public static String camelCase(String str) {
		String[] array = str.toLowerCase().split("_");
		String result = "";
		for (int i = 0; i < array.length; i++) {
			if (i != 0) {
				array[i] = capFirst(array[i]);
			}
			result += array[i];
		}
		return result;
	}
	
	/**
	 * 首字母大写
	 * @param str
	 * @return
	 */
	public static String capFirst(String str) {
		char[] cs = str.toCharArray();
		cs[0] = Character.toUpperCase(cs[0]);
		return String.valueOf(cs);
	}
	
	/**
	 * sha1加密
	 * 
	 * @param content
	 * @return
	 * @throws AesException
	 */
	public static String SHA1(String content) {
		try {
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(content.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 * @return
	 */
	public static String MD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(str.getBytes(DEFAULT_CHARSET));
			StringBuilder sb2 = new StringBuilder();
			for (byte item : array) {
				sb2.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
			}
			return sb2.toString().toUpperCase();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 生成uuid 32位长度
	 * 
	 * @return
	 */
	public static String UUID() {
		return java.util.UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 获取客户端真实IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * str是否 为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		return StringUtils.isBlank(str);
	}

	@SuppressWarnings("rawtypes")
	public static boolean isBlank(List list) {
		return !isNotBlank(list);
	}

	/**
	 * str是否 不为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotBlank(String str) {
		return StringUtils.isNotBlank(str);
	}

	@SuppressWarnings("rawtypes")
	public static boolean isNotBlank(List list) {
		return list != null && list.size() > 0;
	}

	/**
	 * 从互联网获取内容
	 * 
	 * @param url
	 *            网址
	 * @param body
	 *            body提交内容
	 * @return
	 * @throws Exception
	 */
	public static String httpURL(String url, String body) throws Exception {
		URL httpUrl = new URL(url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setRequestMethod(DEFAULT_METHOD);
		httpURLConnection.setConnectTimeout(60000);// 60s超时时间
		httpURLConnection.setReadTimeout(60000);
		httpURLConnection.connect();

		OutputStream outputStream = httpURLConnection.getOutputStream();
		if (body != null) {
			outputStream.write(body.getBytes(DEFAULT_CHARSET));
		}
		// 获取内容
		InputStream inputStream = httpURLConnection.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
		final StringBuffer stringBuffer = new StringBuffer();
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line);
		}
		String resp = stringBuffer.toString();
		if (stringBuffer != null) {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resp;
	}

	/**
	 * 打印一个对象
	 * 
	 * @param obj
	 */
	public static void printObj(Object obj) {
		System.out.println(JSON.toJSONString(obj));
	}

	/**
	 * 复制对象属性
	 * 
	 * @param source
	 * @param target
	 */
	public static void copyProperties(Object source, Object target) {
		BeanUtils.copyProperties(source, target);
	}

	/**
	 * 将对象转换为Map
	 * 
	 * @param source
	 * @return
	 */
	public static Map<String, Object> getMapFromObj(Object source) {
		return JSON.parseObject(JSON.toJSONString(source));
	}

	/**
	 * URL编码
	 * 
	 * @param url
	 * @return
	 */
	public static String urlEncoder(String url) {
		try {
			return URLEncoder.encode(url, DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
		}
		return url;
	}

	/**
	 * URL解码
	 * 
	 * @param url
	 * @return
	 */
	public static String urlDecoder(String url) {
		try {
			return URLDecoder.decode(url, DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
		}
		return url;
	}

	/**
	 * html转义
	 * 
	 * @param str
	 * @return
	 */
	public static String htmlEscape(String str) {
		return HtmlUtils.htmlEscape(str, DEFAULT_CHARSET);
	}

	/**
	 * html反转义
	 * 
	 * @param str
	 * @return
	 */
	public static String htmlUnescape(String str) {
		return HtmlUtils.htmlUnescape(str);
	}

	/**
	 * html反转义
	 * 
	 * @param str
	 * @return
	 */
	public static SysUser getUser() {
		return (SysUser) SecurityUtils.getSubject().getPrincipal();
	}

	public static String getProperties(String key) {
		return PropertiesUtil.get(key);
	}

	public static void main(String[] args) {

		// System.out.println(WebUtil.UUID().length());
		// Test source = new Test("1", "name", 1, "detail",
		// WebUtil.formatShortDate("2017-1-3"), new Date());
		//
		// Map<String, Object> m = getMapFromObj(source);
		// WebUtil.printObj(m);
		//

		System.out.println(htmlUnescape(htmlEscape("<a>士大夫f</a>")));
		// WebUtil.printObj(source);
		// Test target=new Test();
		// BeanUtils.copyProperties(source,target);
		// WebUtil.printObj(target==source);
	}
}
